#!/usr/bin/python3
# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: t -*-

import sys
import mrget
import gstage4
import strict_hwcfg
import strict_portage
import multiprocessing
sys.path.append('/usr/lib64/fpemud-os-sysman')
from fm_util import Util
from fm_util import InfoPrinter
from fm_util import CcacheLocalService
from fm_util import PrintLoadAvgThread
from fm_param import FmConst
from helper_pkg_warehouse import CloudOverlayDb
from stage4_gentoo import TargetFeatureFpemudOs
from stage4_gentoo import FpemudOsCustomActions


# FIMXE:
# 1. change to lop and rop, lop is for debugging
# 2. don't re-probe machine, add parameters

mrget.init(system_or_user=True)

p = InfoPrinter(indent=int(sys.argv[1]))                        # FIXME: print should be done by infoPrinter
arch = sys.argv[2]
profile = sys.argv[3]
stage3File = sys.argv[4]
stage3DigestFile = sys.argv[5]
snapshotFile = sys.argv[6]
workDirPath = sys.argv[7]

overlayDb = CloudOverlayDb()
if not overlayDb.isUpdateComplete():
    overlayDb.update()

machine = strict_hwcfg.probe()

ftFixbug = gstage4.target_features.FixBugs()
ftKernel = gstage4.target_features.UseBbki()
ftPackageManager = gstage4.target_features.UsePortage()
ftServiceManager = gstage4.target_features.UseSystemd()
ftNoDeprecate = gstage4.target_features.DontUseDeprecatedPackagesAndFunctions()
ftPreferGnu = gstage4.target_features.PreferGnuAndGpl()
ftSupportAllTermType = gstage4.target_features.SupportAllTermType()
ftTailorGit = gstage4.target_features.TailorGit(add_items=[
    "http-connection-timeout-extension",
    "robust-extension",
])
ftTailorWget = gstage4.target_features.TailorWget(add_items=[
    "robust-extension",
])
ftTailorRsync = gstage4.target_features.TailorRsync(add_items=[
    "robust-extension",
])
ftFpemudOs = TargetFeatureFpemudOs()

# step
p.printInfo("- Initializing...")
c = CcacheLocalService()
wdir = gstage4.WorkDir(workDirPath, reset=True)
builder = None
if True:
    s = gstage4.Settings()
    s.program_name = FmConst.programName
    s.log_dir = None
    s.verbose_level = 0
    s.host_cpu_core_count = multiprocessing.cpu_count()
    s.host_memory_size = Util.getPhysicalMemorySize() * 1024 * 1024 * 1024
    s.host_cooling_level = 10 if Util.hwcfgHasFan(machine) is not None else 1
    s.host_distfiles_dir = FmConst.distDir
    if c.is_enabled():
        s.host_ccache_dir = c.get_ccache_dir()

    ts = gstage4.TargetSettings()
    ts.arch = arch
    ts.profile = profile
    ts.mirrors = strict_portage.cfg.PortageConfigDir().get_mirrors_obj().get_mirror_mapping()
    ftFixbug.update_target_settings(ts)
    ftKernel.update_target_settings(ts)
    ftPackageManager.update_target_settings(ts)
    ftServiceManager.update_target_settings(ts)
    ftNoDeprecate.update_target_settings(ts)
    ftPreferGnu.update_target_settings(ts)
    ftTailorGit.update_target_settings(ts)
    ftTailorWget.update_target_settings(ts)
    ftTailorRsync.update_target_settings(ts)
    ftFpemudOs.update_target_settings(ts)
    if c.is_enabled():
        # we use ccache if host uses ccache
        ts.build_opts.ccache = True

    builder = gstage4.Builder(s, ts, wdir)

# step
p.printInfo("- Extracting seed stage...")
with gstage4.seed_stages.GentooStage3Archive(stage3File, digest_filepath=stage3DigestFile) as ss:
    builder.action_unpack(ss)

# step
p.printInfo("- Installing gentoo repository...")
gentooRepo = gstage4.repositories.GentooSnapshot(snapshotFile)
builder.action_create_gentoo_repository(gentooRepo)

# step
p.printInfo("- Generating configurations...")
if True:
    builder.action_init_confdir()

# step
p.printInfo("- Installing overlays...")
if True:
    builder.action_create_overlays([
        gstage4.repositories.UserDefinedOverlay("guru", *overlayDb.getOverlayVcsTypeAndUrl("guru")),
        gstage4.repositories.UserDefinedOverlay("mirrorshq-overlay", "git", "https://gitee.com/mirrorshq/gentoo-overlay"),
        gstage4.repositories.UserDefinedOverlay("your-own-os-overlay", "git", "https://gitee.com/your-own-os/gentoo-overlay"),
        gstage4.repositories.UserDefinedOverlay("fpemud-overlay", "git", "https://gitee.com/fpemud/gentoo-overlay"),
    ])

# step
with PrintLoadAvgThread(p.getIndentStr() + "- Updating world..."):
    worldSet = {
        "dev-vcs/git",
        "dev-vcs/subversion",
        "net-misc/wget",
    }
    if c.is_enabled():
        worldSet.add("dev-util/ccache")
    ftPackageManager.update_world_set(worldSet)
    ftServiceManager.update_world_set(worldSet)
    ftSupportAllTermType.update_world_set(worldSet)

    builder.action_update_world(worldSet)

# step: this step does nothing
builder.action_install_kernel()

# step: this step does nothing
builder.action_enable_services(service_list=[])

# step
p.printInfo("- Initializing Fpemud OS...")
s.verbose_level = 2                                                     # FIXME
if True:
    # FIXME, should be integrated into "sysman check" or "sysman init"
    ftPamSuWheelOk = gstage4.target_features.PamSuWheelOk()
    builder.add_and_run_custom_action("pam_su_wheel_ok", ftPamSuWheelOk.get_custom_action())

    builder.add_and_run_custom_action("init_fpemud_os", FpemudOsCustomActions.init_fpemud_os())

    builder.add_and_run_custom_action("robustify_by_barkspider", FpemudOsCustomActions.robustify_by_barkspider())

# step
p.printInfo("- Installing extra packages...")
builder.add_and_run_custom_action("install_extra_packages", FpemudOsCustomActions.install_extra_packages())

# step
p.printInfo("- Cleaning up...")
builder.add_and_run_custom_action("revert_etc_dir", FpemudOsCustomActions.revert_etc_dir())
builder.action_cleanup()

# finish
builder.finish()
